#include "EventLoopThread.h"

EventLoopThread::EventLoopThread(const ThreadInitCallback &cb, const std::string &name)
    : loop_(nullptr)
    , exiting_(false)
    , thread_(std::bind(&EventLoopThread::threadFunc, this), name)
    , mutex_()
    , cond_()
    , callback_(cb)
{

}
EventLoopThread::~EventLoopThread()
{
    exiting_ = true;
    if(loop_ != nullptr)
    {
        loop_->quit();
        thread_.join();
    }
}

EventLoop *EventLoopThread::startLoop()
{
    thread_.start();//开启新线程并执行this->threadFunc()

    EventLoop* loop = nullptr;
    //等待新线程loop初始化完成才能访问loop_
    {
        std::unique_lock<std::mutex> lock(mutex_);
        while(loop_ == nullptr)
        {
            cond_.wait(lock);
        }
        loop = loop_;
    }
    return loop;
}
//下面的方法在单独的新线程中运行
void EventLoopThread::threadFunc()
{
    EventLoop loop;//创建一个独立的eventLoop

    if(callback_)
    {
        callback_(&loop);
    }

    {
        std::unique_lock<std::mutex> lock(mutex_);
        loop_ = &loop;
        cond_.notify_one();
    }
    loop.loop(); //EventLoop loop 开启底层的 Poller

    //loop结束
    std::unique_lock<std::mutex> lock(mutex_);
    loop_ = nullptr;

}